package Algorithm.LinkedListProblem;

/**
 * @Author cj
 * @Date 2021/11/18 20:14
 */
public class removeLastKthNode2 {

    class DoubleNode {
        public int value;
        public DoubleNode pre;
        public DoubleNode next;

        public DoubleNode(int val) {
            this.value = val;
        }
    }

    public static DoubleNode removeLastKthNode2(DoubleNode head, int lastKth) {
        if (head == null || lastKth < 1) {
            return head;
        }
        DoubleNode node = head;
        while (node != null) {
            lastKth --;
            node = node.next;
        }
        // K-N = 0
        if (lastKth == 0) {
            head = head.next;
            head.pre = null;
        } else if (lastKth < 0){ // K-N < 0
            node = head;
            while (lastKth < 0) {
                node = node.next;
                lastKth ++;
            }
            // 删除
            DoubleNode newNode = node.next.next;
            node.next = newNode;
            if (newNode != null) {
                newNode.pre = node;
            }
        }
        return head;
    }
}
